package com.zyzg.config;

import com.zyzg.domain.GpsData;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.index.IndexResolver;
import org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver;

import javax.annotation.Resource;

@Configuration
public class MongoConfig implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    MongoTemplate oneMongoTemplate;

    private static final String TYPEKEY = "_class";
    
    public MongoConfig(MongoTemplate mongoTemplate) {
        IndexOperations indexOps = mongoTemplate.indexOps(GpsData.class);
        IndexResolver resolver = new MongoPersistentEntityIndexResolver(
            mongoTemplate.getConverter().getMappingContext()
        );
        resolver.resolveIndexFor(GpsData.class).forEach(indexOps::ensureIndex);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        MongoConverter converter = oneMongoTemplate.getConverter();
        if (converter.getTypeMapper().isTypeKey(TYPEKEY)) {
            ((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
        }
    }
}